//
//  TSAccountViewController.swift
//  TSProfitProject
//
//  Created by TMS on 2019/11/6.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit
import MJRefresh

class TSAccountViewController: TSBaseViewController {

    var isFirstLoad = true
    let tableHeaderViewH = (STATUSBAR_HEIGHT + 222)
    var alphaView : UIView!
    var titleLabel : UILabel!
    var messageBtn : UIButton!
    var tableController : TSBaseTableViewController!
    var dataSource : [TSNormalCellModel] = []
    
    lazy var headerInfoView : TSAccountInfoView = {
       var headerView = TSAccountInfoView.init(frame: CGRect(x: 0, y: -STATUSBAR_HEIGHT - 222, width: SCREEN_WIDTH, height: STATUSBAR_HEIGHT + 222))
        headerView.backgroundColor = WHITE_COLOR
        return headerView
    }()
    
    lazy var sectionHeaderView : TSAccountSectionHeaderView = {
       var header = TSAccountSectionHeaderView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 250))
        header.delegate = self
        return header
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationController?.delegate = self;
        
        handleDatas()
        configViews()
        configNaviView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        scrollViewDidScroll(tableController.tableView)
        
        requestUserInfo(showHud: isFirstLoad)
        if isFirstLoad == true {
            isFirstLoad = false
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if #available(iOS 13, *) {
            UIApplication.shared.statusBarStyle = .darkContent
        } else {
            UIApplication.shared.statusBarStyle = .default
        }
    }
    
    @objc func logoutAction() {
        
        TSLoginManager.shared.clearUserInfo()
        UIApplication.shared.keyWindow?.rootViewController = TSLoginViewController()
    }
    
    @objc func messageAction() {
        navigationController?.pushViewController(TSNoticeViewController(), animated: true)
    }
    
    @objc func refreshDatas() {
        requestUserInfo(showHud: false)
    }
    
    func getRecordType(title:String) -> TSRecordType {
        switch title {
        case "投注记录":
            return TSRecordType.investType
        case "充值记录":
            return TSRecordType.rechargeType
        case "提现记录":
            return TSRecordType.withdrawType
        case "账变明细":
            return TSRecordType.conversionType
        default:
            return TSRecordType.unknownType
        }
    }
    
    deinit {
        self.navigationController?.delegate = nil
    }

}

// MARK: - UITableViewDelegate
extension TSAccountViewController : UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = dataSource[indexPath.row]

        var vc : TSBaseViewController?
        switch model.title {
        case "中奖记录", "投注记录", "提现记录", "充值记录", "账变明细":
            let recordVc = TSAccountRecordViewController()
            recordVc.recordType = getRecordType(title: model.title)
            vc = recordVc
        case "增加会员":
            vc = TSAccountAddVipViewController()
        case "邀请好友":
            vc = TSInvationViewController()
        case "我的团队":
            vc = TSMyTeamViewController()
        case "安全设置":
            vc = TSSecuritySettingViewController()
        default: break

        }

        if vc != nil {
            self.navigationController?.pushViewController(vc!, animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return sectionHeaderView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 250
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 0.001))
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
}

// MARK: - UITableViewDataSource
extension TSAccountViewController : UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSNormalTableViewCell.self)) as? TSNormalTableViewCell
        if cell == nil {
            cell = TSNormalTableViewCell(style: .default, reuseIdentifier: NSStringFromClass(TSNormalTableViewCell.self))
        }
        
        let model = dataSource[indexPath.row]
        cell!.setupCell(model: model, last: true)
        
        return cell!
    }
    
    
}
 
// MARK: - UIScrollViewDelegate
extension TSAccountViewController : UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        let offsetY = scrollView.contentOffset.y + scrollView.contentInset.top

        let minAlphaOffset : CGFloat = 0;
        let maxAlphaOffset : CGFloat = 40;

//        if offsetY < 0 {
//
//            var rect = headerInfoView.frame
//            rect.origin.y = offsetY - tableHeaderViewH
//            rect.size.height = tableHeaderViewH - offsetY
//            headerInfoView.frame = rect
//            headerInfoView.updateHeaderViewFrame(offsetY: abs(offsetY))
//        }
        
        let alpha = (offsetY - minAlphaOffset) / (maxAlphaOffset - minAlphaOffset);
        alphaView.alpha = alpha;
        if (alphaView.alpha >= 0.6) {
            if #available(iOS 13, *) {
                UIApplication.shared.statusBarStyle = .darkContent
            } else {
                UIApplication.shared.statusBarStyle = .default
            }
            messageBtn.setBackgroundImage(UIImage(named: "account_message_black"), for: .normal)
            titleLabel.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        } else if (alphaView.alpha <= 0.2) {
            UIApplication.shared.statusBarStyle = .lightContent
            messageBtn.setBackgroundImage(UIImage(named: "account_message_normal"), for: .normal)
            titleLabel.textColor = WHITE_COLOR
        }
    }
}

// MARK: - TSAccountSectionHeaderViewDelegate
extension TSAccountViewController : TSAccountSectionHeaderViewDelegate {
    func didClickItem(title: String) {
        print(title)
        switch title {
        case "充值":
            navigationController?.pushViewController(TSRechargeViewController(), animated: true)
        case "提现":
            navigationController?.pushViewController(TSWithDrawViewController(), animated: true)
        case "额度转换":
            navigationController?.pushViewController(TSLimitConvertViewController(), animated: true)
        case "公告":
            navigationController?.pushViewController(TSNoticeViewController(), animated: true)
        default: break
        }
    }
    
}

// MARK: - Network Request
extension TSAccountViewController {

    func requestUserInfo(showHud:Bool) {
        
        if showHud {
            CBToast.showToastAction()
        }
        TSNetworkManager.request(TMSNetworkTools.getUserInfo, showHUD: showHud, success: { (data) in
            
            let responseDic = data as? NSDictionary
            var model = TSLoginModel.deserialize(from: responseDic)!
            model.token = TSLoginManager.shared.token
            model.user_id = TSLoginManager.shared.user_id
            TSLoginManager.shared.setUserModel(model: model)
            
            self.headerInfoView.setupAccountInfoView()
            self.sectionHeaderView.refreshSectionHeaderInfo()
            
            self.requestUpgradeInfo()
                        
        }) { (error) in
            CBToast.hiddenToastAction()
            self.tableController.tableView.mj_header.endRefreshing()
        }
    }
    
    func requestUpgradeInfo() {
        
        TSNetworkManager.request(TMSNetworkTools.getUpgradeInfo, showHUD: false, success: { (data) in
            
            CBToast.hiddenToastAction()
            self.tableController.tableView.mj_header.endRefreshing()
            
            let responseDic = data as? NSDictionary
            let model = TSAccountUpgradeModel.deserialize(from: responseDic)
            self.headerInfoView.updateProgress(model: model!)
            
        }) { (error) in
            CBToast.hiddenToastAction()
            self.tableController.tableView.mj_header.endRefreshing()
        }
    }
}

// MARK: - Initialize
extension TSAccountViewController {
    
    func configNaviView() {
        let naviView = UIView.init()
        naviView.backgroundColor = CLEAR_COLOR
        self.view.addSubview(naviView)
        naviView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(T_NAVBARHEIGHT)
        }
        
        alphaView = UIView.init()
        alphaView.backgroundColor = WHITE_COLOR
        naviView.addSubview(alphaView)
        alphaView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        let barContainer = UIView.init()
        barContainer.backgroundColor = CLEAR_COLOR
        naviView.addSubview(barContainer)
        barContainer.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(NAVIGATIONBAR_HEIGHT)
        }
        
        titleLabel = UILabel.init()
        titleLabel.text = "个人中心"
        titleLabel.textColor = WHITE_COLOR
        titleLabel.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        barContainer.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.centerY.equalToSuperview()
        }
        
        messageBtn = UIButton.init(type: .system)
        messageBtn.setBackgroundImage(UIImage(named: "account_message_normal"), for: .normal)
        messageBtn.addTarget(self, action: #selector(messageAction), for: .touchUpInside)
        messageBtn.setEnlargeEdgeNumber(enlarge: 10)
        barContainer.addSubview(messageBtn)
        messageBtn.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().inset(12)
        }
    }
    
    func configViews() {
        
        UIApplication.shared.statusBarStyle = .lightContent
        
        tableController = TSBaseTableViewController.init(style: .grouped)
        tableController.tableView.contentInset = UIEdgeInsets(top: tableHeaderViewH, left: 0, bottom: 10, right: 0)
        tableController.shouldDisplayEmptyAlert = false
        tableController.tableView.backgroundColor = WHITE_COLOR
        tableController.tableView.delegate = self
        tableController.tableView.dataSource = self
        tableController.tableView.showsVerticalScrollIndicator = false
        tableController.tableView.separatorStyle = .none
        tableController.tableView.tableFooterView = createTableHeaderView()
        view.addSubview(tableController.tableView)
        tableController.tableView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.bottom.equalToSuperview().inset(T_TABBARHEIGHT)
        }
    
        tableController.tableView.addSubview(headerInfoView)

        tableController.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refreshDatas))
        tableController.tableView.mj_header.ignoredScrollViewContentInsetTop = tableHeaderViewH
    }
    
    func handleDatas() {
        let titleArray = ["投注记录", "充值记录", "提现记录", "账变明细", "增加会员", "邀请好友", "我的团队", "安全设置"]
        for index in 0..<titleArray.count {
            let model = TSNormalCellModel.init(title: titleArray[index], value: "", textColor: "#292929", font: UIFont.systemFont(ofSize: 14, weight: .medium))
            dataSource.append(model)
        }
    }
    
    func createTableHeaderView() -> UIView {
        let tableHeaderView = UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 130))
        tableHeaderView.backgroundColor = WHITE_COLOR
        
        let logoutBtn = UIButton.init(type: .system)
        logoutBtn.setTitle("退出登录", for: .normal)
        logoutBtn.setTitleColor(UIColor.hexadecimalColor(hexadecimal: "#989898"), for: .normal)
        logoutBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        logoutBtn.layer.borderColor = UIColor.hexadecimalColor(hexadecimal: "#989898").cgColor
        logoutBtn.layer.borderWidth = 1
        logoutBtn.layer.cornerRadius = 25
        logoutBtn.layer.masksToBounds = true
        logoutBtn.addTarget(self, action: #selector(logoutAction), for: .touchUpInside)
        tableHeaderView.addSubview(logoutBtn)
        logoutBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(50)
            make.size.equalTo(CGSize(width: SCREEN_WIDTH*0.85, height: 50))
        }
        
        return tableHeaderView
    }
}

// MARK: - UINavigationControllerDelegate
extension TSAccountViewController : UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        let isShowHomePage = viewController.isKind(of: TSAccountViewController.self)
        self.navigationController?.setNavigationBarHidden(isShowHomePage, animated: false)
    }
}
